package com.zxkj.commonpatrol.ui;

import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.Observer;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.czy.basecommon.utils.base.BaseVmDataBindingActivity;
import com.czy.basecommon.utils.base.StateData;
import com.czy.basecommon.utils.constant.ItrackConstant;
import com.czy.basecommon.utils.tools.ActivityTool;
import com.czy.basecommon.utils.tools.SPUtils;
import com.czy.basecommon.utils.tools.TimeUtil;
import com.jeremyliao.liveeventbus.LiveEventBus;
import com.xuexiang.xui.widget.dialog.MiniLoadingDialog;
import com.xuexiang.xui.widget.picker.widget.OptionsPickerView;
import com.xuexiang.xui.widget.picker.widget.TimePickerView;
import com.xuexiang.xui.widget.picker.widget.builder.OptionsPickerBuilder;
import com.xuexiang.xui.widget.picker.widget.builder.TimePickerBuilder;
import com.xuexiang.xui.widget.picker.widget.listener.OnOptionsSelectListener;
import com.xuexiang.xui.widget.picker.widget.listener.OnTimeSelectChangeListener;
import com.xuexiang.xui.widget.picker.widget.listener.OnTimeSelectListener;
import com.xuexiang.xui.widget.toast.XToast;
import com.zxkj.commonpatrol.BR;
import com.zxkj.commonpatrol.R;
import com.zxkj.commonpatrol.databinding.ActivityAddCheckPointBinding;
import com.zxkj.commonpatrol.model.entity.SelectProjectEntrity;
import com.zxkj.commonpatrol.model.response.PointCategoryResponse;
import com.zxkj.commonpatrol.viewmodel.AddCheckPointViewModel;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

@Route(path = "/Common/AddCheckPointActivity")
public class AddCheckPointActivity extends BaseVmDataBindingActivity<ActivityAddCheckPointBinding, AddCheckPointViewModel> {

    //查看和编辑 复用
   private  int type=0;//0  查看,1 編輯
    private OptionsPickerView<Object> mVehicleType;
    private int mVehicleTypeOption;
    private  String CategoryCode;
    private HashMap<String, String> hashMap;
    private String RouteCode;//路线COde
    private TimePickerView mTimePicker;
    private MiniLoadingDialog loadingDialog;
    private String proName;
    private String name;
  private  int IsAdd=0;//0编辑 1新增
    private String routeCode;

    @Override
    public int initContentView(Bundle savedInstanceState) {
        return R.layout.activity_add_check_point;
    }

    @Override
    public int initVariableId() {
        return BR.addCheckPointViewModel;
    }

    @Override


    protected void setListener() {
        super.setListener();



        binding.edPointType.setOnClickListener(v -> {
            if (mVehicleType!=null){
                mVehicleType.show();
            }
        });
        binding.btnNo.setOnClickListener(v->{
            if (loadingDialog==null){
                loadingDialog= new MiniLoadingDialog(this, "加載中...");
            }
            loadingDialog.show();

            viewModel.Save(CategoryCode,RouteCode,IsAdd,routeCode);
        });
        binding.edPointCnTime.setOnClickListener(v->{
            if (mTimePicker!=null){
                mTimePicker.show();
            }
        });
        binding.qkBack.setOnClickListener(v->{
            ActivityTool.getInstance().popOneActivity(this);
        });
    }

    @Override
    protected void initUI() {
         if (getIntent().hasExtra("IsEdit")){
             type=getIntent().getIntExtra("IsEdit",0);
         }
        if (getIntent().hasExtra("routeTypeCode")){
            RouteCode=getIntent().getStringExtra("routeTypeCode");
        }
        if (getIntent().hasExtra("IsEdit")){
            type=getIntent().getIntExtra("IsEdit",0);
        }
        if (getIntent().hasExtra("proName")){
            proName=getIntent().getStringExtra("proName");
        }
        if (getIntent().hasExtra("name")){
            name=getIntent().getStringExtra("name");
        }
        if (getIntent().hasExtra("routeCode")){
            routeCode=getIntent().getStringExtra("routeCode");
        }


         if (type==0){
             //查看  编辑
             IsAdd=0;
             binding.tvTitle.setText("查看巡查點");
             binding.c1.setVisibility(View.VISIBLE);
             binding.c2.setVisibility(View.VISIBLE);
             binding.btnNo.setVisibility(View.VISIBLE);
             if (!TextUtils.isEmpty(proName))
             {
                 binding.edPointProject.setText(proName);
             }
             if (!TextUtils.isEmpty(name))
             {
                 binding.edPointProject2.setText(name);
             }

             setCheckFalse(binding.edPointNb,binding.edPointType);
         }else{
             IsAdd=1;
             binding.btnNo.setVisibility(View.VISIBLE);
             binding.c1.setVisibility(View.GONE);
             binding.c2.setVisibility(View.GONE);
             //編輯
             binding.tvTitle.setText("新增巡查點");
             setCheckTrue(binding.edPointNb,binding.edPointCnName,binding.edPointEnName,binding.edPointCnLocation,binding.edPointRl,binding.edPointZb);

         }
        pickUpDate();




    }



    @Override
    protected void initData() {
      if (type==0){
          //查看编辑
          if (loadingDialog==null){
              loadingDialog= new MiniLoadingDialog(this, "加載中...");
          }
          loadingDialog.show();
          viewModel.getTypeList(RouteCode);
          viewModel.SeeDetail(RouteCode);

      }else{
          //新增
         viewModel.getTypeList(RouteCode);
      }
    }

   public void  setCheckFalse(EditText...editTexts){
       for (EditText editText: editTexts) {
            editText.setFocusable(false);
           editText.setEnabled(false);
           editText.setFocusableInTouchMode(false);
       }
   }
    public void  setCheckTrue(EditText...editTexts){
        for (EditText editText: editTexts) {
            editText.setFocusable(true);
            editText.setEnabled(true);
            editText.setFocusableInTouchMode(true);
        }
    }

    @Override
    protected void dataObserver() {
        super.dataObserver();
        viewModel.TypeList.observe(this, new Observer<StateData<List<PointCategoryResponse>>>() {
            @Override
            public void onChanged(StateData<List<PointCategoryResponse>> listStateData) {
                if (listStateData.getStatus()== StateData.DataStatus.SUCCESS){
                    if (listStateData.getData().size()>0){
                        ArrayList<String> list=new ArrayList();
                        hashMap =new HashMap<>();
                        for (int i = 0; i <listStateData.getData().size(); i++) {
                            list.add(listStateData.getData().get(i).getName());
                            hashMap.put(listStateData.getData().get(i).getName(),listStateData.getData().get(i).getCode());
                        }
                        int size4 = list.size();
                        String[] array4 = (String[]) list.toArray(new String[size4]);
                        VehicleType(array4);
                    }
                }
            }
        });
        viewModel.TypeDetail.observe(this, new Observer<StateData<List<PointCategoryResponse>>>() {
            @Override
            public void onChanged(StateData<List<PointCategoryResponse>> listStateData) {
                if (loadingDialog!=null){
                    loadingDialog.dismiss();
                }

            }
        });
        viewModel.TypeSave.observe(this, new Observer<StateData<Object>>() {
            @Override
            public void onChanged(StateData<Object> objectStateData) {
                if (loadingDialog!=null){
                    loadingDialog.dismiss();
                }
                if (objectStateData.getStatus()== StateData.DataStatus.SUCCESS){
                    XToast.success(AddCheckPointActivity.this,"保存成功").show();
                    LiveEventBus.get("refresh").post("1");
                    ActivityTool.getInstance().popOneActivity(AddCheckPointActivity.this);

                }else{
                    XToast.error(AddCheckPointActivity.this,"保存失敗").show();
                }
            }
        });
        viewModel.CategoryCode.observe(this, new Observer<StateData<String>>() {
            @Override
            public void onChanged(StateData<String> stringStateData) {
                if (stringStateData.getStatus()== StateData.DataStatus.SUCCESS){
                    CategoryCode=stringStateData.getData();
                }
            }
        });
    }
    private void VehicleType(final String[] o) {
        mVehicleType = new OptionsPickerBuilder(this, new OnOptionsSelectListener() {
            @Override
            public boolean onOptionsSelect(View view, int options1, int options2, int options3) {
                binding.edPointType.setText(o[options1]);
                mVehicleTypeOption = options1;
                CategoryCode=hashMap.get(o[options1]);
                return false;
            }


        }).setCancelText("取消")//取消按钮文字
                .setSubmitText("確認")//确认按钮文字
                .setTitleText("請選擇路線")
                .setSubCalSize(16)
                .setSubCalSize(16)

                .setSelectOptions(mVehicleTypeOption)
                .build();
        mVehicleType.setPicker(o);

    }

    private void pickUpDate() {

        mTimePicker = new TimePickerBuilder(this, new OnTimeSelectListener() {
            @Override
            public void onTimeSelected(Date date, View v) {

                     binding.edPointCnTime.setText(TimeUtil.getDateByDates(date));


            }
        })
                .setTimeSelectChangeListener(new OnTimeSelectChangeListener() {

                    @Override
                    public void onTimeSelectChanged(Date date) {
                        //不能早於當天
//                        Date nowDate = new Date();
//                        boolean before = date.before(nowDate);
//                        if (before) {
//                            //早于今天
//                            XToast.error(QuickAddActivity.this, getString(R.string.before_time)).show();
//                        }
                    }
                })

                .setType(new boolean[]{true, true, true, false, false, false})
                .isCenterLabel(false)
                .setSubCalSize(16)
                .setSubCalSize(16)
                .setCancelText("取消")//取消按钮文字
                .setSubmitText("確認")//确认按钮文字
                .setLabel("", "", "", "", "", "")
                .setTitleText("請選擇時間")
                .build();

    }
}
